var express = require('express');
var router = express.Router();
let mysql=require('mysql');
let fs =require('fs')
let path=require('path');
let time=require('time-stamp')
let formidable=require('formidable');
let config={
  host:'localhost',
  port:3306,
  user:'root',
  password:'root',
  database:'student'
};
let conn=mysql.createConnection(config);
conn.connect((err)=>{
  if(err){
    console.log('数据库连接失败');
  }else{
    console.log('数据库连接成功');
  }
})
router.get('/upload',(req,res)=>{
  res.render('upload.html')
});
router.post('/upload',(req,res)=>{
  let form=new formidable.IncomingForm();
  form.uploadDir = path.dirname(__dirname);
  console.log(form);
  form.parse(req, (err, files, fildes) => { 
    //console.log(fildes);
    let uploadfile = fildes.pic1;
    console.log(uploadfile);
    //给图片更名
    //时间戳
    let t = time("YYYYMMDD");
    //随机数
    let r = parseInt(Math.random() * 10000);
    //获取文件上传后缀名
    let extname = path.extname(uploadfile.originalFilename);
  if(extname==''){
    res.send('请选择要上传的图片')
  }else{
     // 指定上传新路径地址
    let newpath=path.dirname(__dirname)+"/upload/" + t + r + extname;
    console.log(newpath);
    let newp=path.basename(newpath);
    //获取原来地址
    let oldpath = uploadfile.filepath;
    console.log(oldpath);
    fs.rename(oldpath, newpath, (err) => {
        if (err) {
            res.send("上传失败")
        } else {
            // res.send("上传成功")
            let sql=`insert into zy (path) value ('${newp}')`;
            console.log(sql);
            conn.query(sql,(err)=>{
              if(err){
                res.send('添加失败')
              }else{
                res.redirect('/index');
              }
            })  
        }
    })
  }
   
  }) 
})
module.exports = router;
